var totalPage;
var totalCnt;
var firsteMenuData = [];
var secondMenuData = [];
var deleteFlag = '';
var secondParentMenuID = undefined;
var updateMenuID = undefined;
var delMenuID = undefined;
var addDefault = '';
var levelFlag = '';
//拖动排序
var moveID = undefined;
var moveLeve = undefined;
var moveParentID = undefined;
var moveEventFlag = false;

$(document).ready(function() {
	setBaseUrl();
	$('title', parent.document).html($('title').text());
	searchFirstMenu();
	$("#move2").hide();
});

function searchFirstMenu(){
	$ajax('searchChangeMenuID',{
		LimitCount : 3,
		Level : "button",
		ParentMenuID : 0
	}, searchChangeMenuID);
}

function searchChangeMenuID(data){
	firsteMenuData = data && data.changeIDList || [];
	$("#menuLeftMessage").empty();
	if (firsteMenuData.length > 0) {
		for (var i=0; i<firsteMenuData.length; i++) {
			var data = firsteMenuData[i];
			$("#menuLeftMessage").append("" +
				'<li class="menuLeftLi">' +
				'<div class="firstMenu" id="firstMenu' + i + '" onclick="searchSecondMenu(\'' + data.menuID + '\',\'' + i + '\')">' +
				    '<img src="static/images/menuLine.png" height="12px;" width="12px;"/><span title="' + data.menuName + '">' + data.menuName + '</span></div>' +
				'<div class="secondMenu" id="secondMenu' + data.menuID + '" hidden="hidden">' +
				    '<ul class="firstUl" id="first' + data.menuID + '"></ul>' +
				'</div>' +
				'</li>'
			);
		}
		if (moveEventFlag) {
			moveFlag('move2', 'move1');
		}
	}
//	else {
//		showMessage("没有查询到数据");
//	}
	if (firsteMenuData.length < 3) {
		$("#menuLeftMessage").append("" +
			'<li class="menuLeftLi">' +
			'<div class="firstMenu" onclick="addMenuID(\'button\', \'0\')" style="border-right: 1px solid #e7e7eb;">' +
			'<img src="static/images/menuAdd.png" style="max-width: 20px;max-height: 20px;"/></div>' +
			'</li>'
		);
	}
	getFirstMsg();
}

function getFirstMsg(){
	$("#firstMenu0").click();
}

function addMenuID(level, parentID){
	showLoading();
	$(".secondLi").removeClass("bacd8");
	if (level == "button") {
		$(".secondMenu").hide();
	    $("#MenuName").attr("maxlength", "4");
        $("#MenuMsg").html("字数不超过4个");
	} else if (level == "sub_button") {
	    $("#MenuName").attr("maxlength", "7");
        $("#MenuMsg").html("字数不超过7个");
    }
	$("#showHideParent").show();
	$("#showHideTitle").hide();
	deleteFlag = "save";
	levelFlag = '';
	levelFlag = level;
	initDetalisMsg();
	$("#saveOrUpdate").removeAttr("onclick");
	$("#saveOrUpdate").attr("onclick","saveSure(\'"+ level +"\',\'"+ parentID +"\')");
	setTimeout(hideLoading, 500);
}

function searchSecondMenu(ID, index){
	$("#deleteMenu").removeAttr("onclick");
	if (ID) {
		addDefault = '';
		addDefault = ID + "," + index;
		detalisMsg(firsteMenuData[index]);
		$("#deleteMenu").attr("onclick","deleteMenu(\'"+ ID +"\')");
		secondParentMenuID = ID;
		updateMenuID = ID;
		$("#MenuName").attr("maxlength", "4");
		$("#MenuMsg").html("字数不超过4个");
		if (!levelFlag) {
		    levelFlag = "button";
		}
		$ajax('searchChangeMenuID',{
			LimitCount : 5,
			Level : "sub_button",
			ParentMenuID : ID
		}, searchSecondSign);
	}
}

function searchSecondSign(data){
	secondMenuData = data && data.changeIDList || [];
	$("#first" +  secondParentMenuID).empty();
	$(".secondMenu").hide();
	if (secondMenuData.length > 0 ) {
		for (var i=0; i<secondMenuData.length; i++) {
			var str = '';
			if (i == 4) {
				str = '<div class="triangle-down"></div>'
			}
			var data = secondMenuData[i];
			$("#first" +  secondParentMenuID).append("" +
				'<li class="secondLi" id="secondLi'+ data.menuID + i +'" onclick="secondDetalisMsg(\''+ data.menuID +'\',\''+ i +'\')"><div class="secondDiv">'+ data.menuName +'</div>'+ str +'</li>'
			);
		}
		if (moveEventFlag) {
			moveFlag('move2', 'move1');
		}
		$("#showHideParent").hide();
		$("#showHideTitle").show();
	} else {
		$("#showHideParent").show();
		$("#showHideTitle").hide();
	}
	if (secondMenuData.length < 5 ) {
		$("#first" +  secondParentMenuID).append("" +
			'<li class="secondLi" onclick="addMenuID(\'sub_button\', \''+ secondParentMenuID +'\')">' +
			'<img src="static/images/menuAdd.png" style="max-width: 20px;max-height: 20px;"/>' +
			'<div class="triangle-down"></div>' +
			'</li>'
		);
	}
	$("#secondMenu" +  secondParentMenuID).show();
}
function secondDetalisMsg(ID, Index){
	showLoading();
	$("#deleteMenu").removeAttr("onclick");
	if (ID) {
		$("#showHideParent").show();
		$("#showHideTitle").hide();
		$("#MenuName").attr("maxlength", "7");
		$("#MenuMsg").html("字数不超过7个");
		$(".secondLi").removeClass("bacd8");
		$("#secondLi" + ID + Index).addClass("bacd8");
		detalisMsg(secondMenuData[Index]);
		updateMenuID = ID;
		$("#deleteMenu").attr("onclick","deleteMenu(\'"+ ID +"\')");
	}
	setTimeout(hideLoading, 500);
}
function deleteMenu(ID) {
	if (ID) {
		delMenuID = ID;
		deleteFlag = "delete";
		showMessage(messageContent["Delete.Confirm"], "model2");
	}
}
function getUrl(){
	if(deleteFlag == "save"){
		return 'saveWechatMenu';
	} else if(deleteFlag == "update"){
		return 'updateWechatMenu';
	} else if(deleteFlag == "delete"){
		return 'deleteWechatMenu';
	}
}
function getData(){
	return {menuID: delMenuID, level: levelFlag};
}
function sure(data){
	var result = data && data.result;
	if (result == "Success") {
		showMessage(messageContent["Delete.Success"]);
	} else if (result == "NotFound") {
		showMessage(messageContent["Delete.NotFound"]);
	} else {
		showMessage(messageContent["Delete.Error"]);
	}
	initDetalisMsg();
	searchFirstMenu();
}
function showCondition(){
	$("#appID").empty();
	$("#pagePath").empty();
	if (getMenuType() == 'miniprogram') {
		$("#appIDdiv").show();
		$("#pagePathdiv").show();
	} else {
		$("#appIDdiv").hide();
		$("#pagePathdiv").hide();
	}
}
function initDetalisMsg(){
	$("#MenuName").val('');
	$("#MenuKey").val('');
	$("#Enabled").val('');
	$("#AppID").val('');
	$("#PagePath").val('');
	$("#Url").val('');
	$("#appIDdiv").hide();
	$("#pagePathdiv").hide();
	document.getElementsByName("Type")[0].checked = true;
}
function checkFormMsg(){
	if ($("#MenuName").val() == ''){
		showMessage("菜单名称不能为空！");
		return false;
	}
	if ($("#Enabled").val() == ''){
		showMessage("是否使用不能为空！");
		return false;
	}
//	if ($("#Url").val() == ''){
//		showMessage("地址URL不能为空！");
//		return false;
//	}
	return true;
}
function detalisMsg(data){
	if (data) {
		initDetalisMsg();
		$("#MenuName").val(data.menuName || '未知菜单');
		$("#MenuKey").val(data.menuKey || '未知');
		if (data.enabled) {
			$("#Enabled").val(1);
		} else {
			$("#Enabled").val(0);
		}
		var obj = document.getElementsByName("Type");
		for(var i=0; i<obj.length; i ++){
			if (obj[i].value == data.type) {
				obj[i].checked = true;
				if (obj[i].value == 'miniprogram') {
					$("#appIDdiv").show();
					$("#pagePathdiv").show();
					$("#AppID").val(data.appID || '未知');
					$("#PagePath").val(data.pagePath || '未知');
				} else {
					$("#AppID").val('');
					$("#PagePath").val('');
				}
			}
		}
		$("#Url").val(data.url || '未知');
		$("#saveOrUpdate").removeAttr("onclick")
		$("#saveOrUpdate").attr("onclick","updateSure()");
	}
}
function getMenuType(){
	var obj = document.getElementsByName("Type");
	for(var i=0; i<obj.length; i ++){
		if(obj[i].checked){
			return obj[i].value;
		}
	}
}
function saveSure(level, parentID){
	var MenuType = getMenuType();
	if (checkFormMsg()) {
		$ajax('saveMenu', {
			MenuID: updateMenuID,
			MenuName: $("#MenuName").val(),
			Type: MenuType,
			Level: level,
			ParentMenuID: parentID,
			MenuKey: $("#MenuKey").val(),
			Enabled: $("#Enabled").val(),
			AppID: $("#AppID").val(),
			PagePath: $("#PagePath").val(),
			Url: $("#Url").val()
		}, saveWechatMenu);
	}
}
function updateSure(){
	deleteFlag = "update";
	if (checkFormMsg()) {
		var MenuType = getMenuType();
		$ajax('updateMenu',{
			MenuID : updateMenuID,
			MenuName : $("#MenuName").val(),
			Type : MenuType,
			MenuKey : $("#MenuKey").val(),
			Enabled : $("#Enabled").val(),
			AppID : $("#AppID").val(),
			PagePath : $("#PagePath").val(),
			Url : $("#Url").val()
		}, saveWechatMenu);
	}
}

function saveWechatMenu(data){
	if(deleteFlag == "save"){
		var result = data && data.result;
		if (result == "Success") {
			showMessage(messageContent["Insert.Success"]);
			$('#save').modal('hide');
			formReset("saveForm");
		} else if (result == "NotFound"){
			showMessage(messageContent["Insert.Failed"]);
		} else if (result == "DuplicateError"){
			showMessage(messageContent["Insert.Failed"]);
		} else if (result == "MenuNameExist"){
			showMessage(messageContent["Insert.MenuNameExist"]);
		} else {
			showMessage(messageContent["Insert.Error"]);
		}
	}else if(deleteFlag == "update"){
		var result = data && data.result;
		if (result == "Success"){
			showMessage(messageContent["Update.Success"]);
			$('#save').modal('hide');
			formReset("saveForm");
		} else if (result == "NotFound"){
			showMessage(messageContent["Update.Failed"]);
        } else if (result == "DuplicateError"){
            showMessage(messageContent["Update.Failed"]);
        } else if (result == "MenuNameExist"){
            showMessage(messageContent["Update.MenuNameExist"]);
		} else{
			showMessage(messageContent["Update.Error"]);
		}
	}
	var str = addDefault.split(",");
	if (levelFlag == "button") {
		searchFirstMenu();
	} else if (levelFlag == "sub_button") {
		searchSecondMenu(str[0], str[1]);
	}
}

//拖动
function moveFlag(IDOne, IDTwo){
	moveID = undefined;
	moveLeve = undefined;
	moveParentID = undefined;
	$("#" + IDOne).show();
	$("#" + IDTwo).hide();
	if (IDOne == "move2") {
		if (firsteMenuData.length > 0) {
			$(".firstMenu").attr("draggable", "true");
			$(".secondLi").attr("draggable", "true");
			for (var i = 0; i < firsteMenuData.length; i++) {
				var data = firsteMenuData[i];
				$("#firstMenu" + i).attr("ondragstart","dragStart(event, '"+ data.menuID +"', '"+ data.parentMenuID +"', 'firstMenu', '"+ i +"')");
				$("#firstMenu" + i).attr("ondragenter","dragEnter(event)");
				$("#firstMenu" + i).attr("ondragleave","dragLeave(event)");
				$("#firstMenu" + i).attr("ondragover","allowDrop(event)");
				$("#firstMenu" + i).attr("ondrop","drop(event, \'"+ data.menuID +"\', \'"+ data.orderNumber +"\', '"+ data.parentMenuID +"', 'firstMenu', '"+ i +"')");
			}
			for (var i = 0; i < secondMenuData.length; i++) {
				var data = secondMenuData[i];
				$("#secondLi" + data.menuID + i ).attr("ondragstart","dragStart(event, '"+ data.menuID +"', '"+ data.parentMenuID +"', 'secondLi', '"+ i +"')");
				$("#secondLi" + data.menuID + i ).attr("ondragenter","dragEnter(event)");
				$("#secondLi" + data.menuID + i ).attr("ondragleave","dragLeave(event)");
				$("#secondLi" + data.menuID + i ).attr("ondragover","allowDrop(event)");
				$("#secondLi" + data.menuID + i ).attr("ondrop","drop(event, \'"+ data.menuID +"\', \'"+ data.orderNumber +"\', '"+ data.parentMenuID +"', 'secondLi', '"+ i +"')");
			}
		}
	} else {
		initMoveEvent();
	}
}
function initMoveEvent(){
	moveEventFlag = false;
	$(".firstMenu").removeAttr("ondragstart");
	$(".firstMenu").removeAttr("ondragenter");
	$(".firstMenu").removeAttr("ondragleave");
	$(".firstMenu").removeAttr("ondragover");
	$(".firstMenu").removeAttr("ondrop");
	$(".secondLi").removeAttr("ondragstart");
	$(".secondLi").removeAttr("ondragenter");
	$(".secondLi").removeAttr("ondragleave");
	$(".secondLi").removeAttr("ondragover");
	$(".secondLi").removeAttr("ondrop");
}
function dragStart(event, menuID, parentID, className, index) {
	event.dataTransfer.setData("Text", event.target.id);
	moveID= menuID;
	moveLeve = className;
	moveParentID = parentID;
}

function dragEnter(event) {
	if ( event.target.className == "firstMenu" ) {
		event.target.style.backgroundColor = "cfcbcb";
	}
}

function dragLeave(event) {
	if ( event.target.className == "firstMenu" ) {
		event.target.style.backgroundColor = "";
	}
}

function allowDrop(event) {
	event.preventDefault();
}

function drop(event, menuID, orderNumber, parentID, className, index) {
	event.preventDefault();
	if (moveLeve == className && moveParentID == parentID) {
		$ajax('moveMenu',{
			MenuID : menuID,
			ChangeMenuID : moveID,
			OrderNumber : orderNumber,
			ParentMenuID : parentID
		}, moveMenuSure);
	}
}
function moveMenuSure(data){
	var result = data && data.result;
	if (result == "Success"){
		showMessage(messageContent["Update.Success"]);
		moveEventFlag = true;
		searchFirstMenu();
	} else if (result == "NotFound"){
		showMessage(messageContent["Update.Failed"]);
	} else{
		showMessage(messageContent["Update.Error"]);
	}
}

function publish() {
    $ajax('publishMenu', undefined, publishMenuSure);
}

function publishMenuSure(data){
    var result = data && data.result;
    if (result == "Success"){
		showMessage(messageContent["Publish.Success"]);
	} else if (result == "NotFound"){
		showMessage(messageContent["Publish.NotFound"]);
	} else if (result == "Failed"){
		showMessage(messageContent["Publish.Failed"]);
	} else{
		showMessage(messageContent["Publish.Error"]);
	}
}
